<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input disabled v-model="formData.userId" placeholder="请输入用户ID" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input disabled v-model="formData.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input disabled v-model="formData.mobile" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input disabled v-model="formData.idCard" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-input disabled v-model="formData.birthday" placeholder="请输入出生日期" />
      </el-form-item>
      <el-form-item label="省市区" prop="location">
        <el-input disabled v-model="formData.location" placeholder="请输入省市区（逗号分隔）" />
      </el-form-item>
      <el-form-item label="详细地址" prop="locationDetail">
        <el-input disabled v-model="formData.locationDetail" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="ID号" prop="idCode">
        <el-input disabled v-model="formData.idCode" placeholder="请输入ID号" />
      </el-form-item>
      <el-form-item label="确诊年龄" prop="confirmedDiagnosisAge">
        <el-input disabled v-model="formData.confirmedDiagnosisAge" placeholder="请输入确诊年龄" />
      </el-form-item>
      <el-form-item disabled="" label="状态" prop="status">
        <el-radio-group disabled v-model="formData.status">
          <el-radio :value="true">已分配</el-radio>
          <el-radio :value="false">待分配</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="特病症" prop="specialIllness">
        <el-radio-group disabled v-model="formData.specialIllness">
          <el-radio :value="true">是</el-radio>
          <el-radio :value="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="就诊人标签" prop="locationIds">
        <el-cascader
          v-model="formData.tags"
          :options="tagsTree"
          :props="{ multiple: true }"
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="风险等级" prop="riskLevel">
        <el-radio-group v-model="formData.riskLevel">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_RISK_LEVEL)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider><h3>其它信息</h3></el-divider>
      <el-form-item label="主要病症" prop="mainSymptoms">
        <el-input v-model="formData.mainSymptoms" type="textarea" placeholder="请输入主要病症" />
      </el-form-item>
      <el-form-item label="初始tPSA" prop="initialTpsa">
        <el-input v-model="formData.initialTpsa" placeholder="请输入初始tPSA（ng／ml）" />
      </el-form-item>
      <el-form-item label="睾酮" prop="testosterone">
        <el-input v-model="formData.testosterone" placeholder="请输入睾酮（nmol／L）" />
      </el-form-item>
      <el-form-item label="MRI" prop="mri">
        <el-input v-model="formData.mri" type="textarea" placeholder="请输入MRI" />
      </el-form-item>
      <el-form-item label="穿刺病理" prop="puncturePathology">
        <el-input v-model="formData.puncturePathology" type="textarea" placeholder="请输入穿刺病理" />
      </el-form-item>
      <el-form-item label="临床诊断" prop="clinicalDiagnosis">
        <el-input v-model="formData.clinicalDiagnosis" placeholder="请输入临床诊断" />
      </el-form-item>
      <el-form-item label="危险分层" prop="riskStratification">
        <el-input v-model="formData.riskStratification" placeholder="请输入危险分层" />
      </el-form-item>
      <el-form-item label="首选治疗方案" prop="preferredPlan">
        <el-select
          v-model="formData.preferredPlan"
          placeholder="请选择首选治疗方案"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_PRE_PLAN)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-divider><h3>既往病史</h3></el-divider>
      <el-form-item label="心脑血管系统" prop="xnxgHistory">
        <el-select v-model="formData.xnxgHistory" multiple placeholder="请选择心脑血管系统既往病史">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_XNXG_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="神经系统" prop="sjHistory">
        <el-select v-model="formData.sjHistory" multiple placeholder="请选择神经系统既往病史">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_SJ_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="呼吸系统" prop="hxHistory">
        <el-select v-model="formData.hxHistory" multiple placeholder="请选择呼吸系统既往病史">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_HX_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="消化系统" prop="xhHistory">
        <el-select v-model="formData.xhHistory" multiple placeholder="请选择消化系统">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_XH_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="血液系统" prop="xyHistory">
        <el-select v-model="formData.xyHistory" multiple placeholder="请选择血液系统">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_XY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内分泌系统" prop="nfmHistory">
        <el-select v-model="formData.nfmHistory" multiple placeholder="请选择内分泌系统">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.BUSINESS_USER_PATIENT_NFM_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="其它既往病史" prop="otherHistory">
        <el-input v-model="formData.otherHistory" type="textarea" placeholder="请输入其它既往病史" />
      </el-form-item>
      <el-form-item label="常用药物" prop="commonlyUsedDrugs">
        <el-input v-model="formData.commonlyUsedDrugs" type="textarea" placeholder="请输入常用药物" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import { UserPatientApi, UserPatient } from '@/api/business/userpatient'
import {handleTree} from "@/utils/tree";
import { TagApi, Tag } from '@/api/business/tag'

/** 就诊人 表单 */
defineOptions({ name: 'UserPatientForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  userId: undefined,
  name: undefined,
  mobile: undefined,
  idCard: undefined,
  birthday: undefined,
  location: undefined,
  locationDetail: undefined,
  idCode: undefined,
  confirmedDiagnosisAge: undefined,
  specialIllness: undefined,
  xnxgHistory: undefined,
  sjHistory: undefined,
  hxHistory: undefined,
  xhHistory: undefined,
  xyHistory: undefined,
  nfmHistory: undefined,
  otherHistory: undefined,
  commonlyUsedDrugs: undefined,
  mainSymptoms: undefined,
  initialTpsa: undefined,
  testosterone: undefined,
  mri: undefined,
  puncturePathology: undefined,
  clinicalDiagnosis: undefined,
  riskStratification: undefined,
  preferredPlan: undefined,
  status: undefined,
  doctorId: undefined,
  riskLevel: undefined,
  tags: undefined,
  remark: undefined,
})
const formRules = reactive({
  userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  idCard: [{ required: true, message: '身份证号不能为空', trigger: 'blur' }],
  birthday: [{ required: true, message: '出生日期不能为空', trigger: 'blur' }],
  location: [{ required: true, message: '省市区不能为空', trigger: 'blur' }],
  locationDetail: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  idCode: [{ required: true, message: 'ID号不能为空', trigger: 'blur' }],
  confirmedDiagnosisAge: [{ required: true, message: '确诊年龄不能为空', trigger: 'blur' }],
  specialIllness: [{ required: true, message: '特病症不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const tagsTree = ref() // 树形结构

/** 获得已开通城市树 */
const getTagsTree = async () => {
  tagsTree.value = await TagApi.getTagTree()
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  await getTagsTree();
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserPatientApi.getUserPatient(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserPatient
    if (formType.value === 'create') {
      await UserPatientApi.createUserPatient(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserPatientApi.updateUserPatient(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    name: undefined,
    mobile: undefined,
    idCard: undefined,
    birthday: undefined,
    location: undefined,
    locationDetail: undefined,
    idCode: undefined,
    confirmedDiagnosisAge: undefined,
    specialIllness: undefined,
    xnxgHistory: undefined,
    sjHistory: undefined,
    hxHistory: undefined,
    xhHistory: undefined,
    xyHistory: undefined,
    nfmHistory: undefined,
    otherHistory: undefined,
    commonlyUsedDrugs: undefined,
    mainSymptoms: undefined,
    initialTpsa: undefined,
    testosterone: undefined,
    mri: undefined,
    puncturePathology: undefined,
    clinicalDiagnosis: undefined,
    riskStratification: undefined,
    preferredPlan: undefined,
    status: undefined,
    doctorId: undefined,
    riskLevel: undefined,
    tags: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>
